<template>
  <div class="budget-sheet-form">
    <!-- 顶部卡片 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="title">{{ title }}</div>
          <div class="buttons">
            <el-button :icon="Back" @click="goBack">返回</el-button>
            <el-button v-if="!isViewMode" type="primary" :icon="Check" :loading="submitLoading" @click="submitForm">提交</el-button>
          </div>
        </div>
      </template>
      
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        label-position="right"
        :disabled="isViewMode"
      >
        <!-- 基本信息卡片 -->
        <el-card class="base-info-card" shadow="never">
          <template #header>
            <div class="form-section-header">
              <el-icon><Document /></el-icon>
              <span>基本信息</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="项目名称" prop="projectId">
                <el-select v-model="form.projectId" placeholder="请选择项目" clearable class="full-width">
                  <el-option 
                    v-for="item in projectList" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户名称" prop="customerId">
                <el-select v-model="form.customerId" placeholder="请选择客户" clearable class="full-width">
                  <el-option 
                    v-for="item in customerList" 
                    :key="item.id" 
                    :label="item.companyName" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="业务员" prop="personId">
                <el-select v-model="form.personId" placeholder="请选择业务员" clearable class="full-width">
                  <el-option 
                    v-for="item in personList" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="目标金额" prop="targetAmount">
                <el-input-number v-model="form.targetAmount" :precision="2" :step="1000" :min="0" class="full-width" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="毛利率(%)" prop="grossMargin">
                <el-input-number v-model="form.grossMargin" :precision="2" :step="1" :min="0"  class="full-width" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="销售订单类型" prop="saleType">
                <el-select v-model="form.saleType" placeholder="请选择销售订单类型" clearable class="full-width">
                  <el-option 
                    v-for="item in saleTypeOptions" 
                    :key="item.dictLabel" 
                    :label="item.dictLabel" 
                    :value="item.dictLabel" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="集成规划类型" prop="integratedPlanningType">
                <el-select v-model="form.integratedPlanningType" placeholder="请选择集成规划类型" clearable class="full-width">
                  <el-option 
                    v-for="item in planningTypeOptions" 
                    :key="item.dictLabel" 
                    :label="item.dictLabel" 
                    :value="item.dictLabel" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="订单类型1" prop="orderType">
                <el-select v-model="form.orderType" placeholder="请选择订单类型1" clearable class="full-width">
                  <el-option 
                    v-for="item in orderTypeOptions" 
                    :key="item.dictLabel" 
                    :label="item.dictLabel" 
                    :value="item.dictLabel" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="订单类型2" prop="orderType2">
                <el-select v-model="form.orderType2" placeholder="请选择订单类型2" clearable class="full-width">
                  <el-option 
                    v-for="item in orderType2Options" 
                    :key="item.dictLabel" 
                    :label="item.dictLabel" 
                    :value="item.dictLabel" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="质保期(年)" prop="warrantyPeriodYear">
                <el-input-number v-model="form.warrantyPeriodYear" :min="0" :max="10" class="full-width" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="项目动画视频" prop="projectAnimationVideo">
                <el-select v-model="form.projectAnimationVideo" placeholder="请选择是否有项目动画视频" clearable class="full-width">
                  <el-option label="是" value="是" />
                  <el-option label="否" value="否" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        
        <!-- 费用信息卡片 -->
        <el-card class="fee-info-card" shadow="never">
          <template #header>
            <div class="form-section-header">
              <el-icon><Document /></el-icon>
              <span>费用信息</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="其他费用" prop="otherExpenses">
                <el-input-number v-model="form.otherExpenses" :precision="2" :step="100" :min="0" class="full-width" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="非标颜色费" prop="nonStandardColorFee">
                <el-input-number v-model="form.nonStandardColorFee" :precision="2" :step="100" :min="0" class="full-width" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="营销费用" prop="marketingExpenses">
                <el-select v-model="form.orderType2" placeholder="请选择订单类型2" clearable class="full-width">
                  <el-option 
                    v-for="item in marketingExpensesOptions" 
                    :key="item.dictLabel" 
                    :label="item.dictLabel" 
                    :value="item.dictLabel" 
                  />
                </el-select>              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        
        <!-- 付款信息卡片 -->
        <el-card class="payment-info-card" shadow="never">
          <template #header>
            <div class="form-section-header">
              <el-icon><Document /></el-icon>
              <span>付款信息</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="付款周期(天)" prop="paymentCycle">
                <el-input-number v-model="form.paymentCycle" :min="0" :max="365" class="full-width" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="到货款比例(%)" prop="proportionReceivedPaymentAmount">
                <el-input-number v-model="form.proportionReceivedPaymentAmount" :precision="2" :step="1" :min="0"  class="full-width" />
              </el-form-item>
            </el-col>

          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="付款周期(天)" prop="paymentCycle2">
                <el-input-number v-model="form.paymentCycle2" :min="0" :max="365" class="full-width" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="安装验收款比例" prop="installationAcceptancePaymentRatio">
                <el-input-number v-model="form.installationAcceptancePaymentRatio" :precision="2" :step="1" :min="0"  class="full-width" />
              </el-form-item>
            </el-col>

          </el-row>

          <el-row :gutter="20">
          <el-col :span="12">
              <el-form-item label="质保期(月)" prop="warrantyPeriodMonth">
                <el-input-number v-model="form.warrantyPeriodMonth" :min="0" :max="12" class="full-width" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="质保金比例(%)" prop="warrantyMoney">
                <el-input-number v-model="form.warrantyMoney" :precision="2" :step="1" :min="0"  class="full-width" />
              </el-form-item>
            </el-col>
          </el-row>

          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="承兑时间(月)" prop="acceptanceTime">
                <el-input-number v-model="form.acceptanceTime" :precision="2" :step="1" :min="0"  class="full-width" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="承兑金额" prop="acceptanceMoney">
                <el-input-number v-model="form.acceptanceMoney" :precision="2" :step="1" :min="0"  class="full-width" />

              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { 
  getBudgetSheetDetailApi, 
  addBudgetSheetApi, 
  updateBudgetSheetApi 
} from '@/api/budgetSheet/index'
import type { BudgetSheet, BudgetSheetCreateDTO, BudgetSheetUpdateDTO } from '@/api/budgetSheet/type'
import { Check, Back, Document } from '@element-plus/icons-vue'
import { getListApi as getDictListApi } from "@/api/sysDictData"
import { SysDictData } from "@/api/sysDictData/type"
import { getSimpleProject } from "@/api/project"
import { getSimpleCustomer } from "@/api/companyCustomer"
import { getSimpleUser } from "@/api/user"

// 定义props接收路由传递的display参数
const props = defineProps({
  display: {
    type: String,
    default: 'false'
  }
})

const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const submitLoading = ref(false)
const id = computed(() => route.params.id ? Number(route.params.id) : undefined)
const title = computed(() => {
  if (isViewMode.value) {
    return '查看预算单'
  } else if (id.value) {
    return '编辑预算单'
  } else {
    return '新增预算单'
  }
})

// 是否为查看模式
const isViewMode = computed(() => route.query.display === 'true' || props.display === 'true')

// 项目列表
const projectList = ref<any[]>([])
// 客户列表
const customerList = ref<any[]>([])
// 业务员列表
const personList = ref<any[]>([])
// 销售订单类型选项
const saleTypeOptions = ref<SysDictData[]>([])
// 集成规划类型选项
const planningTypeOptions = ref<SysDictData[]>([])
// 订单类型1选项
const orderTypeOptions = ref<SysDictData[]>([])
// 订单类型2选项
const orderType2Options = ref<SysDictData[]>([])
// 营销费用选项
const marketingExpensesOptions = ref<SysDictData[]>([])

// 表单数据
const form = reactive<BudgetSheet>({
  projectId: undefined,
  customerId: undefined,
  personId: undefined,
  targetAmount: undefined,
  grossMargin: undefined,
  saleType: undefined,
  integratedPlanningType: undefined,
  projectAnimationVideo: undefined,
  orderType: undefined,
  orderType2: undefined,
  warrantyPeriodYear: undefined,
  otherExpenses: undefined,
  nonStandardColorFee: undefined,
  marketingExpenses: undefined,
  paymentCycle: undefined,
  proportionReceivedPaymentAmount: undefined,
  paymentCycle2: undefined,
  installationAcceptancePaymentRatio: undefined,
  warrantyPeriodMonth: undefined,
  acceptanceTime: undefined,
  acceptanceMoney: undefined
})

// 表单校验规则
const rules = reactive<FormRules>({
  projectId: [
    { required: true, message: '请选择项目', trigger: 'change' }
  ]
})

// 获取项目列表
const getProjectOptions = async () => {
  try {
    const res = await getSimpleProject()
    projectList.value = res.data || []
  } catch (error) {
    console.error('获取项目列表失败', error)
  }
}

// 获取客户列表
const getCustomerOptions = async () => {
  try {
    const res = await getSimpleCustomer()
    customerList.value = res.data || []
  } catch (error) {
    console.error('获取客户列表失败', error)
  }
}

// 获取业务员列表
const getPersonOptions = async () => {
  try {
    const res = await getSimpleUser()
    personList.value = res.data || []
  } catch (error) {
    console.error('获取业务员列表失败', error)
  }
}

// 获取字典项
const getDictOptions = async (dictType: string) => {
  try {
    const res = await getDictListApi({ 
      dictType,
      page: 1,
      limit: 1000
    })
    return res.data || []
  } catch (error) {
    console.error(`获取字典${dictType}失败`, error)
    return []
  }
}


// 获取销售订单类型选项
const getSaleTypeOptions = async () => {
  try {
    const res = await getDictListApi({
        dictType: 'saleType',
        dictName: "",
        status: undefined,
        page: 0,
        limit: 100
    })
    if (res && res.data) {
      saleTypeOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取销售订单类型选项失败:', error)
  }
}

// 获取集成规划类型选项
const getPlanningTypeOptions = async () => {
  try {
    const res = await getDictListApi({
        dictType: 'integratedPlanningType',
        dictName: "",
        status: undefined,
        page: 0,
        limit: 100
    })
    if (res && res.data) {
      planningTypeOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取类型列表失败:', error)
  }
}

// 获取订单类型1选项
const getOrderTypeOptions = async () => {
  try {
    const res = await getDictListApi({
        dictType: 'orderType',
        dictName: "",
        status: undefined,
        page: 0,
        limit: 100
    })
    if (res && res.data) {
      orderTypeOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取类型列表失败:', error)
  }
}

// 获取订单类型2选项
const getOrderType2Options = async () => {
  try {
    const res = await getDictListApi({
        dictType: 'orderType',
        dictName: "",
        status: undefined,
        page: 0,
        limit: 100
    })
    if (res && res.data) {
      orderType2Options.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取类型列表失败:', error)
  }
}

// 获取营销费用选项
const getMarketingExpensesOptions = async () => {
  try {
    const res = await getDictListApi({
        dictType: 'marketingExpenses',
        dictName: "",
        status: undefined,
        page: 0,
        limit: 100
    })
    if (res && res.data) {
      marketingExpensesOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取类型列表失败:', error)
  }
}

// 获取预算单详情
const getBudgetSheetDetail = async () => {
  try {
    const res = await getBudgetSheetDetailApi(id.value as number)
    Object.assign(form, res.data)
  } catch (error) {
    console.error('获取预算单详情失败', error)
    ElMessage.error('获取预算单详情失败')
  }
}

// 表单提交
const submitForm = async () => {
  if (!formRef.value) return
  
  formRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true
      
      const submitAction = async () => {
        try {
          if (id.value) {
            // 编辑模式
            const updateData = {
              id: id.value,
              projectId: form.projectId || 0,
              ...form
            } as BudgetSheetUpdateDTO
            await updateBudgetSheetApi(updateData)
            ElMessage.success('更新预算单成功')
          } else {
            // 新增模式
            const createData = {
              projectId: form.projectId || 0,
              ...form
            } as BudgetSheetCreateDTO
            await addBudgetSheetApi(createData)
            ElMessage.success('新增预算单成功')
          }
          goBack()
        } catch (error) {
          console.error('提交预算单失败', error)
          ElMessage.error('提交失败，请检查数据后重试')
        } finally {
          submitLoading.value = false
        }
      }
      
      submitAction()
    } else {
      ElMessage.warning('请完善表单信息')
    }
  })
}

// 返回上一页
const goBack = () => {
  router.push({ path: '/budgetSheet' })
}

onMounted(async () => {
  await getProjectOptions()
  await getCustomerOptions()
  await getPersonOptions()
  await getSaleTypeOptions()
  await getPlanningTypeOptions()
  await getOrderTypeOptions()
  await getOrderType2Options()
  await getMarketingExpensesOptions()
  
  if (id.value) {
    await getBudgetSheetDetail()
  }
})
</script>

<style scoped lang="scss">
.budget-sheet-form {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  
  .box-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .title {
        font-size: 18px;
        font-weight: 600;
      }
      
      .buttons {
        display: flex;
        gap: 10px;
      }
    }
  }
  
  .base-info-card,
  .fee-info-card,
  .payment-info-card {
    margin-bottom: 20px;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    
    .form-section-header {
      display: flex;
      align-items: center;
      gap: 8px;
      font-weight: 600;
      color: #409eff;
    }
  }
}

.full-width {
  width: 100%;
}
</style> 